package com.sinai.mshab.widgets;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Creates a vertical menu.
 * 
 * @author serge
 * 
 */
public class Menu extends VerticalPanel {

	/**
	 * This is used for button retreival based on their name
	 */
	private HashMap<String, MenuButton> nameToButton = new HashMap();

	/**
	 * It's nice to remember all the buttons we have.
	 */
	private ArrayList<MenuButton> buttons = new ArrayList<MenuButton>();

	private Panel container;

	/**
	 * Creates a new menu.
	 */
	public Menu(boolean vertical) {
		if (vertical) {
			setStyleName("mshab-VerticalMenu");
			container = new VerticalPanel();
		} else {
			setStyleName("mshab-HorizontalMenu");
			container = new HorizontalPanel();
		}
		container.setStyleName("mshab-MenuContainer");
		add(container);
	}

	/**
	 * Adds a {@link MenuButton} to this menu.
	 * 
	 * @param button
	 *            the button to be added.
	 */
	public void add(MenuButton button) {
		nameToButton.put(button.getText(), button);
		buttons.add(button);
		container.add(button);
	}

	/**
	 * Adds a {@link MenuHeader} to this menu.
	 * 
	 * @param header
	 *            the header to be added.
	 */
	public void add(MenuHeader header) {
		if (container instanceof VerticalPanel) {
			((VerticalPanel) container).insert(header, 0);
		}
	}

	/**
	 * Returns one of this menu's buttons given the button's text.
	 * 
	 * @param text
	 *            the text of the button you wish to retreive.
	 * @return the button from the menu with the given text.
	 */
	public MenuButton getButton(String text) {
		return nameToButton.get(text);
	}

	/**
	 * Returns one of this menu's buttons given the button's index.
	 * 
	 * @param index
	 *            the index of the button to be returned.
	 * @return the button at the specified index in the menu.
	 */
	public MenuButton getButton(int index) {

		// check that the index is valid.
		if (index >= 0 && index < buttons.size()) {
			return buttons.get(index);
		} else {
			throw new IllegalArgumentException("Bad button index");
		}
	}

	/**
	 * Deselects all the buttons in the menu.
	 */
	public void deselectAll() {
		for (int i = 0; i < buttons.size(); i++) {
			MenuButton curr = buttons.get(i);
			curr.setSelected(false);
		}
	}
}
